package com.hswizy.fishshop.rxjava;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.page.AlibcBasePage;
import com.alibaba.baichuan.android.trade.page.AlibcPage;
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult;
import com.hswizy.fishshop.BuildConfig;
import com.hswizy.fishshop.R;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private WebView webView;
    private ProgressBar progressBar;
    private long backClickTime = 0;
    private ProgressDialog dialog;
    private boolean isCanClick = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPower();
        progressBar = findViewById(R.id.progressbar);//进度条
        dialog = new ProgressDialog(MainActivity.this);
        webView = findViewById(R.id.web_view);
        webView.loadUrl("http://fishshop.lovelytao.com/?_app=sqbao");//加载url
        webView.setWebChromeClient(webChromeClient);
        webView.setWebViewClient(webViewClient);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);//允许使用js
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存，只从网络获取数据.
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
    }

    private void requestPower(){
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url("http://123.206.202.95/api/power?version=" + BuildConfig.VERSION_CODE + "&channel=baidu").build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.equals("0")){
                    isCanClick = false;
                }
            }
        });
    }

    public void showAlibcPage(String couponUrl) {
        AlibcBasePage page = new AlibcPage(couponUrl);
        AlibcShowParams showParams = new AlibcShowParams(OpenType.Native, false);
        AlibcTrade.show(MainActivity.this, page, showParams, null, null, new AlibcTradeCallback() {
            @Override
            public void onTradeSuccess(AlibcTradeResult alibcTradeResult) {

            }

            @Override
            public void onFailure(int i, String s) {

            }
        });
    }

    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (AlibcTrade.isAliUrl(url)){
                if (isCanClick){
                    dialog.setMessage("正在前往淘宝...");
                    dialog.show();
                    showAlibcPage(url);
                }
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

    };

    private WebChromeClient webChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            progressBar.setProgress(newProgress);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (webView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {//点击返回按钮的时候判断有没有上一页
            webView.goBack(); // goBack()表示返回webView的上一页面
            return true;
        }else {
            if (backClickTime == 0 || System.currentTimeMillis() - backClickTime > 3000) {
                Toast.makeText(getBaseContext(),"再按一下退出",Toast.LENGTH_SHORT).show();
                backClickTime = System.currentTimeMillis();
                return true;
            } else {
                backClickTime = 0;
                return super.onKeyDown(keyCode, event);
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (null != dialog){
            dialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.destroy();
        webView = null;
    }
}

